'use client';

import React, { useState } from 'react';

interface SimplePromptGeneratorProps {
  onInsert: (positivePrompt: string, negativePrompt: string) => void;
  placeholder?: string;
}

/**
 * 简化版 AI 提示词生成器
 * 适用于快速集成，减少样式依赖
 */
const SimplePromptGenerator: React.FC<SimplePromptGeneratorProps> = ({
  onInsert,
  placeholder = '输入描述，AI将生成SD提示词...'
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [input, setInput] = useState('');
  const [positive, setPositive] = useState('');
  const [negative, setNegative] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const generatePrompts = async () => {
    if (!input.trim()) {
      setError('请输入描述内容');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/ai-chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [
            {
              role: 'system',
              content: '你是SD提示词生成助手。根据用户描述生成英文正向和反向提示词，格式：{"positive": "正向提示词", "negative": "反向提示词"}'
            },
            {
              role: 'user',
              content: `生成SD提示词：${input}`
            }
          ],
          temperature: 0.7,
          max_tokens: 800
        })
      });

      if (!response.ok) throw new Error('生成失败');

      const reader = response.body?.getReader();
      if (!reader) throw new Error('无法读取响应');

      const decoder = new TextDecoder();
      let content = '';

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ') && line !== 'data: [DONE]') {
            try {
              const data = JSON.parse(line.slice(6));
              if (data.choices?.[0]?.delta?.content) {
                content += data.choices[0].delta.content;
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }

      // 解析生成的内容
      try {
        const jsonMatch = content.match(/\{[^}]*"positive"[^}]*\}/s);
        if (jsonMatch) {
          const result = JSON.parse(jsonMatch[0]);
          setPositive(result.positive || '');
          setNegative(result.negative || 'low quality, blurry, deformed');
        } else {
          setPositive(content.trim());
          setNegative('low quality, blurry, deformed, bad anatomy');
        }
      } catch {
        setPositive(content.trim());
        setNegative('low quality, blurry, deformed, bad anatomy');
      }
    } catch (err: any) {
      setError(err.message || '生成失败');
    } finally {
      setLoading(false);
    }
  };

  const handleInsert = () => {
    onInsert(positive, negative);
    setIsOpen(false);
  };

  const styles = {
    container: {
      position: 'relative' as const,
      display: 'inline-block'
    },
    button: {
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      color: 'white',
      border: 'none',
      padding: '10px 16px',
      borderRadius: '6px',
      cursor: 'pointer',
      fontSize: '14px',
      fontWeight: '500' as const
    },
    modal: {
      position: 'fixed' as const,
      top: '50%',
      left: '50%',
      transform: 'translate(-50%, -50%)',
      background: 'white',
      border: '1px solid #ddd',
      borderRadius: '8px',
      padding: '20px',
      boxShadow: '0 4px 20px rgba(0,0,0,0.15)',
      zIndex: 1000,
      minWidth: '400px',
      maxWidth: '90vw'
    },
    overlay: {
      position: 'fixed' as const,
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'rgba(0,0,0,0.5)',
      zIndex: 999
    },
    input: {
      width: '100%',
      padding: '10px',
      border: '1px solid #ddd',
      borderRadius: '4px',
      marginBottom: '10px',
      fontSize: '14px',
      resize: 'vertical' as const
    },
    generateBtn: {
      background: '#4facfe',
      color: 'white',
      border: 'none',
      padding: '8px 16px',
      borderRadius: '4px',
      cursor: 'pointer',
      marginRight: '10px',
      fontSize: '14px'
    },
    insertBtn: {
      background: '#fa709a',
      color: 'white',
      border: 'none',
      padding: '8px 16px',
      borderRadius: '4px',
      cursor: 'pointer',
      fontSize: '14px'
    },
    closeBtn: {
      background: '#999',
      color: 'white',
      border: 'none',
      padding: '4px 8px',
      borderRadius: '4px',
      cursor: 'pointer',
      float: 'right' as const,
      fontSize: '12px'
    },
    error: {
      color: '#e53e3e',
      fontSize: '12px',
      marginBottom: '10px'
    },
    label: {
      display: 'block',
      marginBottom: '5px',
      fontSize: '13px',
      fontWeight: '600' as const
    }
  };

  return (
    <div style={styles.container}>
      <button style={styles.button} onClick={() => setIsOpen(true)}>
        🤖 AI生成提示词
      </button>

      {isOpen && (
        <>
          <div style={styles.overlay} onClick={() => setIsOpen(false)} />
          <div style={styles.modal}>
            <button style={styles.closeBtn} onClick={() => setIsOpen(false)}>
              ✕
            </button>
            <h3 style={{ margin: '0 0 15px 0' }}>AI提示词生成器</h3>
            
            <textarea
              style={{ ...styles.input, minHeight: '60px' }}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={placeholder}
            />
            
            <button
              style={{
                ...styles.generateBtn,
                opacity: loading ? 0.6 : 1,
                cursor: loading ? 'not-allowed' : 'pointer'
              }}
              onClick={generatePrompts}
              disabled={loading}
            >
              {loading ? '生成中...' : '生成提示词'}
            </button>

            {error && <div style={styles.error}>{error}</div>}

            {(positive || negative) && (
              <div style={{ marginTop: '15px' }}>
                <label style={styles.label}>正向提示词:</label>
                <textarea
                  style={{ ...styles.input, minHeight: '60px' }}
                  value={positive}
                  onChange={(e) => setPositive(e.target.value)}
                />
                
                <label style={styles.label}>反向提示词:</label>
                <textarea
                  style={{ ...styles.input, minHeight: '40px' }}
                  value={negative}
                  onChange={(e) => setNegative(e.target.value)}
                />
                
                <button style={styles.insertBtn} onClick={handleInsert}>
                  插入提示词
                </button>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default SimplePromptGenerator;